<template>
  <div class="main">
    <nav-bar class="home-nav">
      <div class="left" slot="left" @click="goBack">
        <van-icon name="arrow-left" size="24"/>
      </div>
      <div slot="center">打印二维码</div>
    </nav-bar>

    <div class="item_box">
      <div class="flex_between border-bottom pd10">
        <span class="num">批次编号：{{batchInfo.uuid}}</span>
        <span class="num_date">{{batchInfo.create_date}}</span>
      </div>
      <div class="border-bottom flex_between fz14 pd10">
        <span class="">种植基地：<span class="color_main">{{batchInfo.base_name}}</span></span>
      </div>
      <div class="border-bottom flex_between fz14 pd10">
        <span class="">批次名称：<span class="color_main">{{batchInfo.name}}</span></span>
      </div>
      <div class="border-bottom flex_between fz14 pd10">
        <span>开始时间：<span class="color_main">{{batchInfo.start_time}}</span></span>
        <span>结束时间：<span class="color_main">{{batchInfo.end_time}}</span></span>
      </div>

      <div class="create_code" @click="showPopup">点击打印</div>
    </div>

    <!--    <button style="margin-top: 100px;" @click="senBleLabel()">标签打印</button>-->

    <van-dialog v-model="show" title="打印详情" :beforeClose="beforeClose" show-cancel-button>
      <van-field
        readonly
        clickable
        name="picker"
        :value="value"
        label="产品等级"
        placeholder="点击选择等级"
        @click="showPicker = true"
      />
      <p class="no_print">未打印数量<span>{{not_printed_num}}</span>个</p>
      <van-field
        v-model="num"
        type="number"
        name="num"
        label="打印数量"
        placeholder="请输入打印数量"
        :rules="[{ required: true, message: '请填写打印数量' }]"
      />

    </van-dialog>

    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>

  </div>
</template>

<script>
  var tsc = require('@/components/print/tsc.js')
  var esc = require('@/components/print/esc.js')

  import NavBar from "@/components/common/navbar/NavBar"
  import Util from "@/common/util";

  export default {
    name: "printCode",
    components: {
      NavBar
    },

    data() {
      return {
        // againPrint: false,
        indexQR: 1,
        qrcode_url_arr: [],
        connId: '',
        mac_adress: '',
        services: [],
        bid: '',
        pid: '',
        level_id: '',
        num: 0,
        not_printed_num: '',
        value: '',
        columns: [],
        show: false,
        showPicker: false,
        batchInfo: {
          uuid: '',
          name: '',
          create_date: '',
          base_name: '',
          start_time: '',
          end_time: ''
        },
      }
    },

    created() {

      this.pid = this.$route.query.pid;
      this.base_id = this.$route.query.base_id;
      this.bid = this.$route.query.bid;
      this.mac_adress = Util.storage.get('mac_adress');
      //  alert(this.mac_adress)
      this.onOpenBLE();
      this.getLevel();
      this.getBatchInfo();
    },

    methods: {
      getBatchInfo() {
        console.log('进入获取列表')
        let that = this;
        that.$http.get('/api/MobileAadminApi/getBatchtDeail', {id: that.bid}, r => {
          console.log(r)
          that.batchInfo = r.data;
        })
      },

      getLevel() {
        let that = this;
        console.log('进入等级')
        that.$http.get('/api/MobileAadminApi/getLevelList', null, r => {
          console.log('等级r', r)
          let columns = [];
          r.data.map(item => {
            let Obj = {};
            Obj['id'] = item.id;
            Obj['text'] = item.name
            columns.push(Obj);
            // return columns;
          })
          that.columns = columns;
          that.value = r.data[0].name;
          that.level_id = r.data[0].id;
          that.getNotPrinted()
        })
      },

      getNotPrinted() {
        console.log('进入未打印')
        let that = this;
        that.$http.get('/api/MobileAadminApi/getNotPrintQrcodeNum', {
          batch_id: that.bid,
          level_id: that.level_id
        }, r => {
          console.log(r)

          that.not_printed_num = r.data;
        })
      },

      beforeClose(action, done) {
        let that = this;
        if (action === 'confirm') {
          if (that.num == 0) {
            that.$toast('生成数量不能为0！');
            done(false);
            return;
          }
          if (that.num > that.not_printed_num) {
            that.$toast('数量不能超过未打印数');
            done(false);
            return;
          }
          if (that.level_id == '') {
            that.$toast('请选择等级！');
            done(false);
            return;
          }
          const params = {
            batch_id: that.bid,
            level_id: that.level_id,
            num: that.num
          };
          console.log('params' + JSON.stringify(params));

          that.$http.post('/api/MobileAadminApi/setPrintQrcodeNum', params, r => {
            console.log('确认打印：' + JSON.stringify(r))
            //  console.log('666',r)
            that.qrcode_url_arr = r.data;

            that.senBleLabel(r.data[0].qrcode_url)

            //console.log('执行完打印')

            setTimeout(done, 500);
            console.log('准备跳转')
            this.$router.replace({
              path: '/refresh',
              query: {
                base_id: that.base_id,
                pid: that.pid,
                bid: that.bid,
                t: Date.now()
              }
            });

            that.$toast(r.info)
          });

        } else {
          done();
        }
      },

      goBack() {
        this.$router.go(-1);
      },

      showPopup() {
        if (this.mac_adress == '') {
          this.$dialog.confirm({
            title: '提示',
            message: '未连接打印机，请先连接打印机再打印',
          })
            .then(() => {
              this.$router.push('/print')
            })
            .catch(() => {
              // on cancel
            });
          return
        }
        this.show = true
      },

      onConfirm(value) {
        this.value = value['text'];
        this.level_id = value['id'];
        this.showPicker = false;
        this.getNotPrinted()
      },

      destroyed: function () {
        console.log("destroyed----------")
        if (this.connId != '') {
          plus.bluetooth.closeBLEConnection({
            deviceId: this.connId,
            success(res) {
              console.log(res)
            }
          })
        }
      },

      onOpenBLE() {
        let that = this;
        plus.bluetooth.openBluetoothAdapter({
          success(res) {
            console.log("打开 蓝牙模块")
            // console.log('打开蓝牙'+res)
            // that.onDevice()
            plus.bluetooth.getBluetoothAdapterState({
              success: function (res) {
                // console.log(res)
                if (res.available) {
                  if (res.discovering) {
                    that.stopFindBule()
                  }
                  //搜索蓝牙
                  //开始搜寻附近的蓝牙外围设备
                  // console.log("开始搜寻附近的蓝牙外围设备")
                  // plus.bluetooth.startBluetoothDevicesDiscovery({
                  //   success(res) {
                  //     console.log(res)
                  //   }
                  // })

                } else {
                  console.log('本机蓝牙不可用')
                }
              },
            })
          }
        })
        that.onConn();
      },

      onConn() {
        var that = this;
        console.log("连接蓝牙---------------" + that.mac_adress);
        let deviceId = that.mac_adress;
        plus.bluetooth.createBLEConnection({
          deviceId: deviceId,
          timeout: 12000,
          success: function (res) {
            console.log('create connection success: ' + JSON.stringify(res));
          },
          fail: function (e) {
            console.log('create connection failed: ' + JSON.stringify(e));
          },
          complete(res) {
            console.log('create connection complete: ' + JSON.stringify(res));

            if (res.message == "ok") {
              console.log("连接蓝牙-[" + deviceId + "]--成功")
              that.connId = deviceId;
              // that.currDev = item
              setTimeout(function () {
                that.getBLEServices(deviceId)
              }, 2000)
            } else if (res.code == 10012) {
              that.$dialog.alert({
                title: '提示',
                message: '打印机连接超时，请重新连接',
              })
                .then(() => {
                  that.$router.push('/print')
                })
            }
            //连接成功 关闭搜索
            that.stopFindBule()

          },
        })
      },

      getBLEServices(_deviceId) {
        var that = this;
        let deviceId = _deviceId
        console.log("获取蓝牙设备所有服务(service)。---------------")

        plus.bluetooth.getBLEDeviceServices({
          // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
          deviceId: deviceId,
          complete(res) {
            console.log(res)
            let serviceId = ""
            for (var s = 0; s < res.services.length; s++) {
              console.log(res.services[s].uuid)
              let serviceId = res.services[s].uuid
              //console.log(JSON.stringify(that.serviceId))
              plus.bluetooth.getBLEDeviceCharacteristics({
                // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                deviceId: deviceId,
                // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                serviceId: serviceId,
                success(res) {
                  var re = JSON.parse(JSON.stringify(res))
                  console.log('deviceId = [' + deviceId + ']  serviceId = [' + serviceId + ']')

                  for (var c = 0; c < re.characteristics.length; c++) {
                    if (re.characteristics[c].properties.write == true) {
                      let uuid = re.characteristics[c].uuid;
                      console.log(' deviceId = [' + deviceId + ']  serviceId = [' + serviceId + '] characteristics=[' +
                        uuid)
                      that.services.push({
                        serviceId: serviceId,
                        characteristicId: uuid
                      })

                      //  console.log(JSON.stringify(that.devices))
                    }
                  }
                }
              })
            }
          },
          fail(res) {
            console.log(res)
          },
        })
      },

      stopFindBule() {
        console.log("停止搜寻附近的蓝牙外围设备---------------")
        plus.bluetooth.stopBluetoothDevicesDiscovery({
          success(res) {
            console.log(res)
          }
        })
      },

      onAgainPrint() {  //循环打印
        console.log('进入循环打印')
        let that = this;

        for (let i = 1; i < this.qrcode_url_arr.length; i++) {
          console.log('继续循环')
          console.log(JSON.stringify('i:' + i))
          console.log('that.indexQR:' + JSON.stringify(that.indexQR))
          if (i == that.indexQR) {
            that.indexQR++;
            console.log('that.indexQR++' + JSON.stringify(that.indexQR))
            console.log('123qrcode_url' + JSON.stringify(that.qrcode_url_arr[i].qrcode_url))
            that.senBleLabel(that.qrcode_url_arr[i].qrcode_url)
            console.log('函数执行完后')
            break;
          }

        }

      },

      senBlData(deviceId, serviceId, characteristicId, uint8Array) {
        let that = this;
        console.log('打印时：deviceId = [' + deviceId + ']  serviceId = [' + serviceId + '] characteristics=[' + characteristicId + "]")
        var uint8Buf = Array.from(uint8Array);

        function split_array(datas, size) {
          var result = {};
          var j = 0
          for (var i = 0; i < datas.length; i += size) {
            result[j] = datas.slice(i, i + size)
            j++
          }
          //console.log(result)
          return result
        }

        var sendloop = split_array(uint8Buf, 20);

        // console.log(sendloop.length)
        function realWriteData(sendloop, i) {
          var data = sendloop[i]
          console.log('data' + JSON.stringify(typeof (data)))
          if (typeof (data) == "undefined") {
            if (that.qrcode_url_arr.length > 1 && that.indexQR < that.qrcode_url_arr.length) {
              //that.againPrint = true;
              //that.indexQR = 1;
              setTimeout(that.onAgainPrint, 1000)
              //that.onAgainPrint();
            }
            return
          }
          console.log("第【" + i + "】次写数据" + data)
          var buffer = new ArrayBuffer(data.length)
          var dataView = new DataView(buffer)
          for (var j = 0; j < data.length; j++) {
            dataView.setUint8(j, data[j]);
          }
          plus.bluetooth.writeBLECharacteristicValue({
            deviceId,
            serviceId,
            characteristicId,
            value: buffer,
            success(res) {
              realWriteData(sendloop, i + 1);
            }
          })
        }

        var i = 0;
        realWriteData(sendloop, i);
      },

      senBleLabel(content) {
        //标签模式
        let that = this;
        let currDev = Util.storage.get('currDev');
        console.log('currDev' + JSON.stringify(currDev))

        console.log('进入打印方法')
        let deviceId = this.mac_adress;
        console.log('1进入打印方法')

        let serviceId = currDev.services[0].serviceId;
        let characteristicId = currDev.services[0].characteristicId;
        console.log('2进入打印方法')
        let command = tsc.jpPrinter.createNew()
        console.log('3进入打印方法')
        command.setSize(40, 30)
        command.setGap(2)
        command.setCls()
        // command.setText(50, 10, "TSS24.BF2", 1, 1, "打印")
        command.setQR(85, 30, "L", 6, "A", content)
        command.setPagePrint()
        console.log('4进入打印方法')
        that.senBlData(deviceId, serviceId, characteristicId, command.getData())
        console.log('5进入打印方法')
      },

    }
  }
</script>

<style scoped>
  .item_box {
    margin: 10px;
    background: #ffffff;
    border-radius: 8px;
    overflow: hidden;
  }

  .flex_between {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .num {
    font-size: .32rem;
    color: #000000;
  }

  .num_date {
    font-size: .28rem;
  }

  .create_code {
    height: .8rem;
    line-height: .8rem;
    font-size: .36rem;
    color: #ffffff;
    text-align: center;
    background: var(--color-tint);
  }

  .no_print {
    font-size: .28rem;
    padding: 10px 15px;
    background: #f9f9f9;
  }

  .no_print span {
    color: var(--color-tint)
  }
</style>
